package com.imyours.users.session;

import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;

/**
 * 用户登录状态管理类
 * 
 * @author Slevenc
 * 
 */
public class UserSessionManager {
	// singleton
	private static UserSessionManager singleton = null;

	public static UserSessionManager getInstance() {
		if (singleton == null) {
			singleton = new UserSessionManager();
		}
		return singleton;
	}

	// logger
	private static Logger logger = LoggerFactory.getLogger(UserSessionManager.class);

	// 私有构造函数
	private UserSessionManager() {
		init();
	}

	private void init() {
		this.sessionMap = new HashMap<String, UserEntity>();
		this.userMap = new HashMap<String, String>();
		this.timeoutMap = new HashMap<String, Date>();

	}

	/**
	 * sessionID-实体对象
	 */
	private Map<String, UserEntity> sessionMap = null;

	/**
	 * username-sessionID
	 */
	private Map<String, String> userMap = null;

	/**
	 * 用户最后操作时间表 sessionID-最后操作时间
	 */
	private Map<String, Date> timeoutMap = null;

	public UserEntity getUser(String sessionID) {
		UserEntity user = null;
		if (sessionMap.containsKey(sessionID)) {
			user = sessionMap.get(sessionID);
			timeoutMap.put(sessionID, new Date());
		}
		return user;
	}

	private static final String SESSION_ID_DIC = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKMNOPQRSTUVWXYZ";
	private static final int SESSION_ID_LEN = 128;

	public String login(String username, String password) {
		// TODO 优化连接池
		Session s = HibernateUtil.getSessionFactory().openSession();
		List<UserEntity> us = s.createQuery("from UserEntity as ue where ue.username = ? and ue.password = ?").setString(0, username).setString(1, password).list();
		String newSessionId = null;
		if (us.size() == 1) {
			UserEntity user = us.get(0);
			String userName = user.getUsername();
			if (userMap.containsKey(userName)) {
				// 作废同用户的sessionID
				String oldSessionID = userMap.get(userName);
				sessionMap.remove(oldSessionID);
				timeoutMap.remove(oldSessionID);
				userMap.remove(userName);
			}
			// 新用户登录
			newSessionId = getNewSessionID();
			userMap.put(user.getUsername(), newSessionId);
			sessionMap.put(newSessionId, user);
			timeoutMap.put(newSessionId, new Date());
		}
		s.close();
		return newSessionId;
	}

	public void logout(String sessionID) {
		UserEntity ue = null;
		ue = sessionMap.remove(sessionID);
		timeoutMap.remove(sessionID);
		if (ue != null) {
			userMap.remove(ue.getUsername());
		}
	}
	
	
	/**某用户是否在线
	 * @param user
	 * @return
	 */
	public boolean isOnline(UserEntity user){
		return userMap.containsKey(user.getUsername());
	}
	
	/**获取全部在线用户的列表
	 * @return
	 */
	public Collection<UserEntity> getOnlineList(){
		return sessionMap.values();
	}

	/**获取新的随机生成的SessionId;
	 * @return
	 */
	private String getNewSessionID() {
		StringBuilder sb = new StringBuilder();
		boolean repeat = true;
		do {
			sb.setLength(0);
			for (int i = 0; i < SESSION_ID_LEN; i++) {
				int rand = (int) ((Math.random() * 1000) % SESSION_ID_DIC.length());
				sb.append(SESSION_ID_DIC.charAt(rand));
			}
				repeat = sessionMap.containsKey(sb.toString());
		} while (repeat == true);
		return sb.toString();
	}
}
